package com.itxs.utils;

import com.itxs.annotation.ItxsSelect;
import org.springframework.beans.factory.FactoryBean;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ItxsFactoryBean implements FactoryBean {

    private Class mapper;

    public ItxsFactoryBean(Class mapper) {
        this.mapper = mapper;
    }

    @Override
    public Object getObject() throws Exception {
        //使用动态代理机制
        Object o = Proxy.newProxyInstance(ItxsFactoryBean.class.getClassLoader(), new Class[]{mapper}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if (Object.class.equals(method.getDeclaringClass())){
                    return method.invoke(this,args);
                }
                ItxsSelect annotation = method.getAnnotation(ItxsSelect.class);
                System.out.println("调用方法名称是"+method.getName()+",sql语句为"+annotation.value());
                //后面可执行Mybatic操作数据库的相关操作
                return null;
            }
        });
        return o;
    }

    @Override
    public Class<?> getObjectType() {
        return mapper;
    }
}
